#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../include/test.h"
void addNode(int file_descriptor_no){ //returns parent of the added Node

	int i=0,j=0, current_file_descriptor_no = 0 ,temp,currentNodeInserted;
	struct Node* traverse = vfs , *tempNode;
	
	if(vfs == NULL){
		vfs = (struct Node*)malloc(sizeof(struct Node));
		vfs->file_descriptor_no = atoi(header.fd[0].location_path );
		vfs->child = NULL;
		vfs->sibling = NULL;
		
	}
	/*else if(vfs->child == NULL){
		vfs->child = (struct Node*)malloc(sizeof(struct Node));
		vfs->child->file_descriptor_no = file_descriptor_no;
	}*/
	else{
	   
		//tempNode = traverse;
		while(header.fd[i].file_descriptor_no != file_descriptor_no) //Searching for the correct file descriptor
			i++;
		for(j = 2; j < strlen(header.fd[i].location_path);){ // Traversing the entire location path of the considered file descriptor . Where path is of the form 1/2/3/4
		    tempNode = traverse; // TRAVERSE SHOULD ALWAYS POINT TO THE PARENT OF THE NODE TO BE ADDED . 
			current_file_descriptor_no = atoi(header.fd[i].location_path + j);
			temp = current_file_descriptor_no;
			
			struct Node* curNode = (struct Node*)malloc(sizeof(struct Node)); // This is the node we are interested in adding
			curNode->file_descriptor_no = current_file_descriptor_no;
			curNode->sibling = NULL;
			curNode->child = NULL;
			currentNodeInserted = 0;
			while(temp != 0){ //This increment in j accounts to the no of digits in the current file descriptor
				temp =temp/10;
				j++;
			}
			j++; //This increment in j accounts to the single character i.e filetype=directory
        /*    if(tempNode == NULL){
                tempNode = curNode;
				currentNodeInserted = 1;
            }
			else */if(tempNode->child == NULL){
				tempNode->child = curNode;
				currentNodeInserted = 1;
			}
			tempNode = tempNode->child;
			if(tempNode->file_descriptor_no == current_file_descriptor_no){ //If the current node itself is the node we are searching for
				traverse = tempNode;
			}
			else{
			    if(tempNode->file_descriptor_no > current_file_descriptor_no){
			        traverse->child = curNode;
			        curNode->sibling = tempNode;
			        traverse = curNode;
			    }
			    else{
				    while((tempNode->sibling != NULL) && (tempNode->sibling->file_descriptor_no < current_file_descriptor_no) ){
					    tempNode = tempNode->sibling;
				    }
				    if(tempNode->sibling == NULL){
					    tempNode->sibling = curNode;
					    currentNodeInserted = 1;
				    }
				    else if (tempNode->sibling->file_descriptor_no > current_file_descriptor_no ){
					    curNode->sibling = tempNode->sibling;
					    tempNode->sibling = curNode;
					    currentNodeInserted = 1;
				    }
				    if(tempNode->sibling->file_descriptor_no == current_file_descriptor_no){
					    traverse = tempNode->sibling;
				    }
				}
			}
			if(currentNodeInserted == 0){
				free(curNode); //freeing the memory of current Node
			}
		}
				
	}

}	
